package com.hkd.blogsystem.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

@Slf4j
public class SecurityUtils {

    public static String encrypt(String password)  {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return salt + secretString;
    }
    //验证

    public static boolean verify(String password,String finalPassword) {
        if(finalPassword!=null && finalPassword.length() != 64){
            log.error("密码非法长度，存在恶意攻击");
            return false;
        }
        String salt = finalPassword.substring(0, 32);//盐值


        String secretString = null;//校验
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("getBytes 异常”： ",e);
            throw new RuntimeException(e);
        }


        return (salt+secretString).equals(finalPassword);

    }
}
